package com.xcjh.utils;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

/**
 * freemarker工具类
 */
public class FreemarkerUtil {

    private static final Logger log = LoggerFactory.getLogger(FreemarkerUtil.class);

    public static void test(String[] args) throws Exception {
        Map<String,Object> params =new HashMap<>();
        params.put("name","张三");
        System.out.println(readTemplate("template/test.ftl",params));
    }

    /**
     * 读取freemarker模板
     * @param fileName 模板所在目录  例如（template/模板名称.ttl）
     * @param model 模板要使用的变量数据, ftl文件里面 变量以美元符号+大括号表示
     * @return
     * @throws Exception
     */
    public static String readTemplate(String fileName, Map<String, Object> model) throws Exception {

        StringWriter stringWriter = new StringWriter();

        try {
            Configuration cfg = new Configuration(Configuration.VERSION_2_3_28);

            //模板所在目录 这里是放在resources/static目录下
            String templatePath = ResourceUtils.getURL("classpath:").getPath();
            //String templatePath = ClassUtils.getDefaultClassLoader().getResource("static").getPath();

            cfg.setLocale(Locale.CHINA);
            cfg.setEncoding(Locale.CHINA, "UTF-8");
            cfg.setDefaultEncoding("UTF-8");
            cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
            cfg.setLogTemplateExceptions(false);
            cfg.setWrapUncheckedExceptions(true);
            cfg.setClassicCompatible(true);
            cfg.setTagSyntax(Configuration.AUTO_DETECT_TAG_SYNTAX);
            cfg.setWhitespaceStripping(true);
            cfg.setDirectoryForTemplateLoading(new File(templatePath));

            Template temp = cfg.getTemplate(fileName);
            temp.process(model, stringWriter);
            stringWriter.flush();
            return stringWriter.toString();

        } catch (Exception e) {
            log.error(e.getMessage());
        } finally {
            try {
                stringWriter.close();
            } catch (IOException ex) {
                log.error(ex.getMessage());
            }
        }
        return null;
    }
}
